package com.animerank.service.impl;

import com.animerank.entity.Anime;
import com.animerank.entity.Nomination;
import com.animerank.mapper.NominationMapper;
import com.animerank.mapper.VoteMapper;
import com.animerank.service.IAnimeService;
import com.animerank.service.IUserActivityService;
import com.animerank.service.INominationService;
import com.animerank.dto.Result;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.dev33.satoken.stp.StpUtil;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提名服务实现类
 */
@Service
public class NominationServiceImpl extends ServiceImpl<NominationMapper, Nomination> implements INominationService {
    
    @Autowired
    private IAnimeService animeService;
    
    @Autowired
    private IUserActivityService userActivityService;
    
    @Autowired
    private VoteMapper voteMapper;

    @Override
    public Result<?> nominate(Anime anime) {
        // 检查用户是否登录
        if (!StpUtil.isLogin()) {
            return Result.fail(401, "请先登录");
        }
        
        // 获取当前登录用户的ID
        Long userId = StpUtil.getLoginIdAsLong();
        Long animeId = anime.getId();
        
        // 检查用户是否已经提名过该动漫
        Integer nominationCount = this.baseMapper.checkUserNomination(userId, animeId);
        if (nominationCount != null && nominationCount > 0) {
            return Result.fail("您已经提名过这部动漫了");
        }
        
        // 检查动漫是否存在，如果不存在则使用前端传来的完整信息创建
        Anime existingAnime = animeService.getById(animeId);
        if (existingAnime == null) {
            // 保存完整的动漫信息
            anime.setCreatedAt(LocalDateTime.now());
            // 确保即使某些字段为null也能正常保存
            animeService.save(anime);
        } else {
            // 全面更新所有可能的字段，不仅限于几个基本字段
            // 标题
            if (anime.getTitle() != null && !anime.getTitle().isEmpty()) {
                existingAnime.setTitle(anime.getTitle());
            }
            // 描述和详细简介
            if (anime.getDescription() != null) {
                existingAnime.setDescription(anime.getDescription());
            }
            if (anime.getSynopsis() != null) {
                existingAnime.setSynopsis(anime.getSynopsis());
            }
            // 封面图片URL - 确保能被正确保存，无论是否为空字符串
            if (anime.getCoverImageUrl() != null) {
                existingAnime.setCoverImageUrl(anime.getCoverImageUrl());
            }
            // 发布日期
            if (anime.getReleaseDate() != null) {
                existingAnime.setReleaseDate(anime.getReleaseDate());
            }
            // 年份和季度
            if (anime.getYear() != null) {
                existingAnime.setYear(anime.getYear());
            }
            if (anime.getSeason() != null) {
                existingAnime.setSeason(anime.getSeason());
            }
            // 其他可能的信息
            if (anime.getGenre() != null) {
                existingAnime.setGenre(anime.getGenre());
            }
            if (anime.getDirector() != null) {
                existingAnime.setDirector(anime.getDirector());
            }
            if (anime.getStudio() != null) {
                existingAnime.setStudio(anime.getStudio());
            }
            if (anime.getEpisodes() != null) {
                existingAnime.setEpisodes(anime.getEpisodes());
            }
            if (anime.getTags() != null) {
                existingAnime.setTags(anime.getTags());
            }
            // 更新动漫信息
            animeService.updateById(existingAnime);
        }
        
        // 创建提名记录
        Nomination nomination = new Nomination();
        nomination.setUserId(userId);
        nomination.setAnimeId(animeId);
        nomination.setNominatedAt(LocalDateTime.now());
        
        // 保存提名记录
        boolean saved = save(nomination);
        
        if (saved) {
            // 获取动漫信息
            Anime savedAnime = animeService.getById(animeId);
            if (savedAnime != null) {
                // 记录用户活动
                userActivityService.recordActivity(userId, "nomination", animeId, savedAnime.getTitle(), null);
            }
            return Result.success("提名成功");
        } else {
            return Result.fail("提名失败");
        }
    }

    @Override
    public Result<Map<String, Object>> getUserNominations(Integer page, Integer pageSize) {
        // 检查是否登录
        if (!StpUtil.isLogin()) {
            return Result.fail(401, "请先登录");
        }

        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 计算偏移量
        int offset = (page - 1) * pageSize;
        
        // 查询用户的提名记录
        List<Nomination> nominationList = this.baseMapper.getUserNominations(userId, offset, pageSize);
        int total = this.baseMapper.countUserNominations(userId);
        
        // 转换为完整的动漫信息列表
        List<Anime> animeList = new ArrayList<>();
        for (Nomination nomination : nominationList) {
            // 获取动漫详情
            Result<Anime> animeResult = animeService.getAnimeDetail(nomination.getAnimeId());
            if (animeResult.getCode() == 200 && animeResult.getData() != null) {
                Anime anime = animeResult.getData();
                // 查询实际票数
                Integer voteCount = voteMapper.countAnimeVotes(nomination.getAnimeId());
                anime.setVotes(voteCount != null ? voteCount : 0);
                animeList.add(anime);
            }
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("data", animeList);
        result.put("total", total);
        
        return Result.success(result);
    }

}